package com.xuebank.nfe.nfecar.beas

/**
 * Created by Wind_Fantasy on 15/3/26.
 */
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.FrameLayout
import com.trello.rxlifecycle.components.support.RxFragment
import com.wzn.libaray.utils.Logger
import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.utils.loading.ProgressDailog
import com.xuebank.nfe.nfecar.utils.loading.PromptView


abstract class BaseFragment : RxFragment(), View.OnClickListener, AdapterView.OnItemClickListener, IBaseView {

    var TAG = javaClass.simpleName

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        Logger.d(TAG, TAG + "  onCreateView")
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        Logger.d(TAG, TAG + "  onActivityCreated")
        initData(savedInstanceState)
        findViews()
        initViews()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mPromptView?.parent?.let {
            (it as ViewGroup).removeView(mPromptView)
        }

        getContentRootView()?.addView(mPromptView)
    }

    override fun onResume() {
        super.onResume()
        Logger.d(TAG, TAG + "  onResume")
    }

    override fun onPause() {
        super.onPause()
        Logger.d(TAG, TAG + "  onPause")
    }

    override fun onDestroyView() {
        cleanDataOnHide()
        super.onDestroyView()
        Logger.d(TAG, TAG + "  onDestroyView")
    }

    override fun onDestroy() {
        super.onDestroy()
        Logger.d(TAG, TAG + "  onDestroy")
    }

    override fun onDetach() {
        super.onDetach()
        Logger.d(TAG, TAG + "  onDetach")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        Logger.d(TAG, TAG + "  onHiddenChanged")
    }

    protected abstract fun initData(savedInstanceState: Bundle?)

    protected abstract fun initViews()
    protected abstract fun findViews()


    protected open fun cleanDataOnHide() {}


    fun <T : View> findParentActViewById(id: Int): T? {
        return activity?.findViewById<T>(id)
    }


    fun back() {
        fragmentManager?.popBackStack(javaClass.simpleName, FragmentManager.POP_BACK_STACK_INCLUSIVE)
        //		getFragmentManager().beginTransaction().setCustomAnimations(R.anim.act_anim_in2, R.anim.act_anim_out2).remove(BaseFragment.this).commit();
    }

    protected fun <T : View> findViewById(id: Int): T {
        return if (view != null)
            view!!.findViewById<T>(id)
        else
            findParentActViewById<View>(id) as T
    }

    protected fun getRequestFailAlertDialog(positiveClick: DialogInterface.OnClickListener) {
        AlertDialog.Builder(activity).setMessage("请求失败")
                .setPositiveButton("重新请求", positiveClick).setNegativeButton("取消") { dialog, which ->
            var dialog = dialog
            dialog!!.cancel()
            dialog = null
        }.create().show()
    }


    protected fun checkActivity(activity: Activity?): Boolean =
            null != activity && activity is BaseActivity

    /**
     * 是否可以继续执行

     * @return
     */
    override fun canGoon(): Boolean = !(!isAdded || isRemoving || isDetached)

    // variable to track event time
    private var mLastClickTime: Long = 0

    //View.OnClickListener.onClick method defination

    override fun onClick(v: View) {
        // Preventing multiple clicks, using threshold of 1 second
        if (SystemClock.elapsedRealtime() - mLastClickTime < 500) {
            return
        }

        mLastClickTime = SystemClock.elapsedRealtime()

        onViewClick(v)
    }

    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        // Preventing multiple clicks, using threshold of 1 second
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
            return
        }

        mLastClickTime = SystemClock.elapsedRealtime()

        onItemViewClick(parent, view, position, id)
    }

    fun onRightTextViewClick() {}

    fun onItemViewClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {}

    open fun onViewClick(v: View) {

    }

    fun <T> findFragmentByTag(tag: String): T? {
        var fragment: Fragment? = activity?.supportFragmentManager?.findFragmentByTag(tag)
        if (null == fragment)
            fragment = fragmentManager?.findFragmentByTag(tag)
        if (null == fragment)
            fragment = childFragmentManager.findFragmentByTag(tag)
        return fragment as T?
    }


    fun onBackPressed(): Boolean {
        var flag = false
        val fragmentManager = childFragmentManager
        if (null != fragmentManager) {
            val stackCount = fragmentManager.backStackEntryCount
            if (stackCount != 0) {
                val fragment = fragmentManager.findFragmentByTag(fragmentManager.getBackStackEntryAt(stackCount - 1).name)
                if (null != fragment && fragment is BaseFragment) {
                    if (!fragment.onBackPressed()) {
                        fragmentManager.popBackStack()
                    }
                } else {
                    fragmentManager.popBackStack()
                }
                flag = true
            }
        }
        return flag
    }


    val packageName: String?
        get() = context.packageName


    private val mPromptView: PromptView? by lazy {
        PromptView(context)
    }
    private var mProgressDailog: ProgressDailog? = null

//    fun <T> loadingDialogManager(failedAction: (() -> Unit)? = null): Observable.Transformer<T, T> {
//        return Observable.Transformer<T, T> { observable ->
//            observable.doOnSubscribe { showProgressDialog() }.subscribeOn(AndroidSchedulers.mainThread())
//                    .doOnUnsubscribe { dismissProgressDialog() }.doOnCompleted { dismissProgressDialog() }
//                    .doOnError {
//                        dismissProgressDialog()
//                        failedAction?.let { getPromptView()?.onLoadingFailed(failedAction) }
//                    }
//        }
//    }

    override fun getPromptView(): PromptView? = mPromptView

    override fun getProgressDialog(): ProgressDailog? = mProgressDailog

    override fun showProgressDialog() {
        showProgressDialog(0)
    }

    override fun showProgressDialog(textId: Int) {
        var mutableTextId: Int = textId
        if (mutableTextId == 0) mutableTextId = R.string.common_pls_wait
        if (mProgressDailog == null) {
            mProgressDailog = ProgressDailog(context)
        }
        mProgressDailog?.setCanceledOnTouchOutside(false)
        mProgressDailog?.setContent(getString(mutableTextId))
        mProgressDailog?.show()
    }

    override fun showProgressDialog(msg: String?) {
        if (mProgressDailog == null) {
            mProgressDailog = ProgressDailog(activity)
        }
        mProgressDailog?.setCanceledOnTouchOutside(false)
        mProgressDailog?.setContent(msg)
        mProgressDailog?.show()
    }

    override fun dismissProgressDialog() {
        if (mProgressDailog != null) {
            mProgressDailog?.dismiss()
        }
    }

    override fun getContext(): BaseActivity = super.getContext() as BaseActivity

    open fun getContentRootView(): FrameLayout?=null
}

